package com.raincat.toolsdemo.vaccin;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;

import com.google.gson.Gson;
import com.raincat.tools.nettools.HttpsConfig;
import com.raincat.tools.nettools.NetCallBack;
import com.raincat.toolsdemo.R;
import com.raincat.toolsdemo.tools.BaseInfo;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

/**
 * <pre>
 *     author : RainCat
 *     org    : Shenzhen JingYu Network Technology Co., Ltd.
 *     e-mail : nining377@gmail.com
 *     time   : 2020/08/16
 *     desc   : 医院列表
 *     version: 1.0
 * </pre>
 */
public class HospitalListActivity extends AppCompatActivity {
    private Context context;
    private ListView lv_hospital;
    private EditText et_test;

    private ListAdapter listAdapter;
    private HospitalListBean hospitalListBean;
    private HashMap<Integer, String> stringMap = new HashMap<>();
    private Gson gson;
    private SharedPreferences preferences;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hospitallist_main);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        context = HospitalListActivity.this;
        gson = new Gson();
        preferences = PreferenceManager.getDefaultSharedPreferences(context);

        BaseInfo.cityInfo = BaseInfo.getCityByName("南宁市");

        init();
        listener();
        getHospitalList();
    }

    private void init() {
        et_test = findViewById(R.id.et_test);
        lv_hospital = findViewById(R.id.lv_hospital);

        String token = preferences.getString("token", "");
        et_test.setText(token);
    }

    private void listener() {
        lv_hospital.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Intent intent = new Intent(context, HospitalDetailActivity.class);
                intent.putExtra("hospitalId", hospitalListBean.getList().get(position).getId());
                startActivity(intent);
            }
        });

        findViewById(R.id.btn_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_test.setText("");
            }
        });

        findViewById(R.id.btn_test).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                testToken();
            }
        });

        findViewById(R.id.btn_refresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getHospitalList();
            }
        });
    }

    private void testToken() {
        HashMap<String, Object> header = new HashMap<>();
        header.put("Referer", BaseInfo.refererUrl);
        header.put("Cookie", "ASP.NET_SessionId=" + et_test.getText());
        new HttpsConfig().doGet(BaseInfo.getUserInfo)
                .headers(header).start(context, new NetCallBack() {
            @Override
            public void result(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.getInt("status") == 200) {
                        Toast.makeText(context, "测试成功", Toast.LENGTH_SHORT).show();
                        preferences.edit().putString("token", et_test.getText().toString()).apply();
                    } else
                        Toast.makeText(context, "测试失败", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(context, "测试失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void error(int errorCode, String error) {
                Toast.makeText(context, "测试失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getHospitalList() {
        HashMap<String, Object> header = new HashMap<>();
        header.put("Referer", BaseInfo.refererUrl);
        HashMap<String, Object> param = new HashMap<>();
        param.put("act", "CustomerList");
        param.put("city", BaseInfo.cityInfo.city);
        param.put("lat", BaseInfo.cityInfo.lat);
        param.put("lng", BaseInfo.cityInfo.lng);
        param.put("cityCode", BaseInfo.cityInfo.cityCode);
        param.put("id", 0);
        param.put("product", 1);
        new HttpsConfig().doGet(BaseInfo.otherUrl, param)
                .headers(header).start(context, new NetCallBack() {
            @Override
            public void result(String result) {
                hospitalListBean = gson.fromJson(result, HospitalListBean.class);
                if (hospitalListBean != null && hospitalListBean.getList() != null && hospitalListBean.getList().size() != 0) {
                    listAdapter = new ListAdapter(hospitalListBean.getList());
                    lv_hospital.setAdapter(listAdapter);
                } else {
                    Toast.makeText(context, "获取失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void error(int errorCode, String error) {
                Toast.makeText(context, error, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getHospitalDetail(final HospitalListBean.ListBean listBean) {
        if (stringMap.get(listBean.getId()) != null)
            return;

        stringMap.put(listBean.getId(), "");
        HashMap<String, Object> header = new HashMap<>();
        header.put("Referer", BaseInfo.refererUrl);
        HashMap<String, Object> param = new HashMap<>();
        param.put("lat", BaseInfo.cityInfo.lat);
        param.put("lng", BaseInfo.cityInfo.lng);
        param.put("id", listBean.getId());
        param.put("act", "CustomerProduct");
        new HttpsConfig().doGet(BaseInfo.otherUrl, param)
                .headers(header).start(context, new NetCallBack() {
            @Override
            public void result(String result) {
                HospitalDetailBean hospitalDetailBean = gson.fromJson(result, HospitalDetailBean.class);
                if (hospitalDetailBean != null && hospitalDetailBean.getList() != null && hospitalDetailBean.getList().size() != 0) {
                    for (HospitalDetailBean.ListBean bean : hospitalDetailBean.getList()) {
                        if (bean.getText().contains("九价") && !bean.getDate().contains("暂无")) {
                            stringMap.put(listBean.getId(), bean.getDate());
                            break;
                        }
                    }
                    listAdapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(context, "获取失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void error(int errorCode, String error) {
                stringMap.put(listBean.getId(), null);
                getHospitalDetail(listBean);
            }
        });
    }

    private class ListAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        private List<HospitalListBean.ListBean> mList;

        ListAdapter(List<HospitalListBean.ListBean> l) {
            mInflater = LayoutInflater.from(context);
            mList = l;
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder;
            if (convertView == null) {
                holder = new Holder();
                convertView = mInflater.inflate(R.layout.activity_hospitallist_item, parent, false);
                holder.text = convertView.findViewById(R.id.tv_item);
                holder.time = convertView.findViewById(R.id.tv_time);
                convertView.setTag(holder);
            } else
                holder = (Holder) convertView.getTag();

            final HospitalListBean.ListBean listBean = mList.get(position);
            holder.text.setText("名称：" + listBean.getCname() + "\n地址：" + listBean.getAddr() + "\n电话：" + listBean.getTel());

            if (stringMap.get(listBean.getId()) == null) {
                getHospitalDetail(listBean);
                holder.time.setVisibility(View.GONE);
            } else if (stringMap.get(listBean.getId()).length() == 0) {
                holder.time.setText("------暂无九价疫苗------");
                holder.time.setVisibility(View.VISIBLE);
            } else {
                holder.time.setText("时间：" + stringMap.get(listBean.getId()));
                holder.time.setVisibility(View.VISIBLE);
            }

            return convertView;
        }

        class Holder {
            TextView text, time;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
